package leetcode.labuladong;

/**
 * 寻找一个数
 * @author : zx
 * @version V1.0
 */
public class 二分查找 {

    static int binarySearch(int[] nums, int target){
        int left = 0, right = nums.length-1;
        while(left <= right){
            int mid = left + (right-left)/2;
//            if(nums[mid] == target) return mid; // 这种只能返回一个 无法找到边界
            if(nums[mid] == target) right = mid-1; // 收缩右边界 锁定左边界 从而寻找最左的边界值
            else{
                if(nums[mid] < target) left = mid+1;
                else right = mid-1;
            }
        }
        // 检查出界情况
        if(left >= nums.length || nums[left] != target) return -1;
        return left;
    }

    public static void main(String[] args){
        System.out.println(binarySearch(new int[]{1,2,2,2,3}, 2));
    }
}
